#include "head.h"

// 分析用户发来的信息
int analyse(int sock_fd, int epoll_fd, pool_t* pool, MYSQL* mysql, time_queue_t* time_queue, time_hash_t* hash)
{
    LOG_MSG("分析用户发来的信息");
    messenger_t msg; 
    bzero(&msg, sizeof(msg));

    int count = recv(sock_fd, &msg, sizeof(msg), MSG_WAITALL);
    printf("count = %d\n", count);
    if(count == 0)
    {
        printf("对方已断开连接\n");
        epoll_del(epoll_fd, sock_fd);
        close(sock_fd);
        return 0;
    }
    ERROR_CHECK(count, -1, "recv");
       
    // 请求过来 查找 hash 表， 移动 循环队列， 更新 hash表 的时间
    time_t old_t;
    find_time_hash(hash, sock_fd, &old_t);

    time_t new_t = time(NULL);
    update_time_hash(hash, sock_fd, new_t);
    move_time_queue(time_queue, sock_fd, old_t, new_t);
    

    // 检查 TOKEN 
    cmd_t cmd = msg.cmd;
    printf("args: %s\n", msg.args);
    printf("token: %s\n", msg.token);
    switch(cmd)
    {
    case LOGIN: to_login(&msg, sock_fd, mysql);  break;
    case REGISTER: to_register_(&msg, sock_fd, mysql);  break;
    //case LS: to_ls(&node->msg, node->val, mysql);  break;
    //case UP: to_up(&node->msg, node->val, mysql);  break;
    case MKDIR: to_mkdir(&msg, sock_fd, mysql);  break;
    case CD: to_cd(&msg, sock_fd, mysql);  break;
    //case RM: to_rm(&node->msg, node->val, mysql);  break;

    case LS: to_ls(&msg, sock_fd, mysql);    printf("ls 结束\n");   break; 
    case UP:

        // 如果是长命令 移除 epoll 监听 剔除出 hash 表 和 循环队列
        epoll_del(epoll_fd, sock_fd);
        time_t t;
        find_time_hash(hash, sock_fd, &t);
        eliminate_time_hash(hash, sock_fd);
        eliminate_time_queue(time_queue, sock_fd, t);
        close(sock_fd);

        //printf("交给子线程\n");
        pthread_mutex_lock(&pool->mutex);
        push_queue(pool->q, sock_fd, msg);
        pthread_mutex_unlock(&pool->mutex);
        pthread_cond_broadcast(&pool->cond);
    }

    return 0;


    return 0;
}